using FytSoa.Application.Crm.Param;
using FytSoa.Common.Enum;
using FytSoa.Common.Extensions;
using FytSoa.Domain.Crm;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Masuit.Tools;
using Masuit.Tools.Reflection;
using Masuit.Tools.Strings;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Crm;

/// <summary>
/// 项目任务服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v7")]
public class CrmProjectTaskService : IApplicationService 
{
    private readonly SugarRepository<CrmProjectTask> _thisRepository;
    private readonly SugarRepository<CrmProject> _projectRepository;
    private readonly CrmOperateLogService _operateLogService;
    public CrmProjectTaskService(SugarRepository<CrmProjectTask> thisRepository
        ,SugarRepository<CrmProject> projectRepository
    ,CrmOperateLogService operateLogService)
    {
        _thisRepository = thisRepository;
        _projectRepository = projectRepository;
        _operateLogService = operateLogService;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<CrmProjectTaskDto>> GetPagesAsync(CrmProjectTaskSearchParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(param.Id!=0,m=>m.ProjectId==param.Id)
            .WhereIF(param.Stage!=0,m=>m.StageId==param.Stage)
            .WhereIF(param.Type==1,m=>m.ManagerEmployeeId==AppUtils.LoginId)
            .WhereIF(!string.IsNullOrEmpty(param.Status) && param.Status!="-1",m=>m.Status==(CrmProjectTaskStatusEnum)int.Parse(param.Status))
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Number.Contains(param.Key) || m.Name.Contains(param.Key))
            .Includes(m=>m.Stage)
            .Includes(m=>m.Project)
            .Includes(m=>m.ManagerEmployee)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<CrmProjectTaskDto>>();
    }
    
    /// <summary>
    /// 查询所有
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<CrmProjectTaskDto>> GetListAsync(CrmProjectTaskSearchParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(param.Id!=0,m=>m.ProjectId==param.Id)
            .WhereIF(param.Stage!=0,m=>m.StageId==param.Stage)
            .WhereIF(param.Type==1,m=>m.ManagerEmployeeId==AppUtils.LoginId)
            .WhereIF(!string.IsNullOrEmpty(param.Status) && param.Status!="-1",m=>m.Status==(CrmProjectTaskStatusEnum)int.Parse(param.Status))
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Number.Contains(param.Key) || m.Name.Contains(param.Key))
            .Includes(m=>m.Stage)
            .Includes(m=>m.Project)
            .Includes(m=>m.ManagerEmployee)
            .OrderBy(m=>m.Id)
            .ToListAsync();
        return query.Adapt<List<CrmProjectTaskDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<CrmProjectTaskDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(m=>m.ManagerEmployee)
            .Includes(m=>m.Project)
            .FirstAsync(m=>m.Id==id);
        return model.Adapt<CrmProjectTaskDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task AddAsync(CrmProjectTaskDto model)
    {
        model.Number = StringUtils.RandomString(5).ToLower();
        var taskId= await _thisRepository.InsertReturnSnowflakeIdAsync(model.Adapt<CrmProjectTask>());
        
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = taskId,
            Type = (int)OaOperateEnum.Task,
            Remark = "创建了项目任务"
        });
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task ModifyAsync(CrmProjectTaskDto model)
    {
        await _thisRepository.UpdateAsync(model.Adapt<CrmProjectTask>());
        
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = model.Id,
            Type = (int)OaOperateEnum.Task,
            Remark = "修改了项目任务"
        });
    }

    /// <summary>
    /// 更改任务状态
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task ModifyStatusAsync(CrmProjectTaskStatusParam model)
    {
        //判断项目状态
        var task = await _thisRepository.GetByIdAsync(model.Id);
        var project = await _projectRepository.GetByIdAsync(task.ProjectId);
        if (project.Status==CrmProjectStatusEnum.NotStarted)
        {
            throw new BusinessException("项目还没有开始，变更项目状态后才可以更改任务状态！");
        }
        await _thisRepository.UpdateAsync(m => new CrmProjectTask()
        {
            Status = model.Status
        },m=>m.Id==model.Id);
        
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = model.Id,
            Type = (int)OaOperateEnum.Task,
            Remark = "变更了项目任务状态为："+model.Status.GetDescription()
        });
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task DeleteAsync([FromBody] List<long> ids)
    {
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
        var logRepository = _thisRepository.ChangeRepository<SugarRepository<CrmOperateLog>>();
        await logRepository.DeleteAsync(m => ids.Contains(m.OperateId));
    }
}
